<template>
  <div class="h-screen flex bg-bg">
    <!-- 移动端遮罩层 -->
    <div v-if="showSidebar" class="fixed inset-0 bg-black/50 z-40 lg:hidden" @click="showSidebar = false"></div>
    
    <!-- 侧边栏 -->
    <aside :class="[
      'bg-white shadow-lg flex flex-col transition-transform duration-300 z-50',
      'fixed lg:static inset-y-0 left-0 w-64',
      showSidebar ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
    ]">
      <div class="px-4 py-6 border-b flex items-center justify-between">
        <div class="text-xl lg:text-2xl font-semibold text-text">宝宝时光机</div>
        <button class="lg:hidden p-2" @click="showSidebar = false">×</button>
      </div>
      <nav class="flex-1 p-4 space-y-2">
        <RouterLink 
          :class="getMenuItemClass('/')" 
          to="/" 
          @click="showSidebar = false"
        >
          首页
        </RouterLink>
        <RouterLink 
          :class="getMenuItemClass('/timeline')" 
          to="/timeline" 
          @click="showSidebar = false"
        >
          时光轴
        </RouterLink>
        <RouterLink 
          :class="getMenuItemClass('/stats')" 
          to="/stats" 
          @click="showSidebar = false"
        >
          数据统计
        </RouterLink>
        <RouterLink 
          :class="getMenuItemClass('/gallery')" 
          to="/gallery" 
          @click="showSidebar = false"
        >
          美好时刻
        </RouterLink>
        <RouterLink 
          :class="getMenuItemClass('/settings')" 
          to="/settings" 
          @click="showSidebar = false"
        >
          家庭与设置
        </RouterLink>
        <button class="block w-full text-left px-3 py-2 rounded hover:bg-bg text-red-600" @click="handleLogout">退出登录</button>
      </nav>
    </aside>
    
    <!-- 主内容区 -->
    <div class="flex-1 flex flex-col min-w-0">
      <!-- 移动端顶部栏 -->
      <header class="lg:hidden bg-white shadow-sm px-4 py-3 flex items-center justify-between">
        <button @click="showSidebar = true" class="p-2">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
          </svg>
        </button>
        <div class="text-lg font-semibold text-text">宝宝时光机</div>
        <div class="w-10"></div>
      </header>
      
      <main class="flex-1 overflow-y-auto p-3 lg:p-6">
        <router-view />
      </main>
    </div>
  </div>
  
  <!-- 悬浮操作按钮 -->
  <div class="fixed bottom-6 right-6 z-30">
    <!-- 主按钮 -->
    <button
      class="w-14 h-14 rounded-full bg-accent text-black shadow-lg hover:opacity-90 transition-all duration-200"
      @click="toggleFab"
      :class="{ 'rotate-45': showFab }"
      aria-label="快捷操作"
      title="快捷操作"
    >
      <span class="text-2xl font-bold">+</span>
    </button>
    
    <!-- 展开菜单 -->
    <div v-if="showFab" class="absolute bottom-16 right-0 space-y-3 animate-fade-in">
      <!-- AI助手 -->
      <button
        class="flex items-center gap-3 px-4 py-3 bg-white rounded-full shadow-lg hover:shadow-xl transition-all duration-200 min-w-[140px]"
        @click="goToAIChat"
        title="AI智能助手"
      >
        <span class="text-2xl">🤖</span>
        <span class="text-sm font-medium text-gray-700">AI助手</span>
      </button>
      
      <!-- 回到主页 -->
      <button
        class="flex items-center gap-3 px-4 py-3 bg-white rounded-full shadow-lg hover:shadow-xl transition-all duration-200 min-w-[140px]"
        @click="goToHome"
        title="回到主页"
      >
        <span class="text-2xl">🏠</span>
        <span class="text-sm font-medium text-gray-700">回到主页</span>
      </button>
    </div>
  </div>
  
  <!-- AI对话悬浮窗口 -->
  <div v-if="showAIChat" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click="showAIChat = false">
    <div class="ai-chat-window bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col" @click.stop>
      <!-- 窗口头部 -->
      <div class="flex items-center justify-between p-4 border-b">
        <div class="flex items-center gap-2">
          <span class="text-2xl">🤖</span>
          <span class="text-lg font-semibold">AI智能助手</span>
        </div>
        <button @click="showAIChat = false" class="p-2 hover:bg-gray-100 rounded-full">
          <span class="text-xl">×</span>
        </button>
      </div>
      
      <!-- 对话区域 -->
      <div class="flex-1 overflow-y-auto p-4 space-y-4" ref="chatContainer">
        <!-- 欢迎消息 -->
        <div v-if="!aiMessages.length" class="text-center text-gray-500 py-8">
          <div class="text-4xl mb-2">🤖</div>
          <div class="text-sm">我是您的AI育儿助手，有什么问题可以问我哦！</div>
        </div>
        
        <!-- 对话消息 -->
        <div v-for="(msg, index) in aiMessages" :key="index" class="space-y-4">
          <!-- 时间分隔符 -->
          <div v-if="shouldShowTime(index)" class="flex justify-center">
            <div class="text-xs text-gray-400 bg-gray-100 px-3 py-1 rounded-full">
              {{ formatTime(msg.timestamp) }}
            </div>
          </div>
          
          <!-- 用户消息 -->
          <div v-if="msg.user" class="flex justify-end items-end gap-2">
            <div class="flex flex-col items-end">
              <div class="message-bubble bg-blue-500 text-white px-4 py-2 rounded-2xl max-w-[80%]">
                {{ msg.user }}
              </div>
            </div>
            <div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center text-white text-sm font-medium shadow-md">
              👤
            </div>
          </div>
          
          <!-- AI消息 -->
          <div v-if="msg.ai" class="flex justify-start items-end gap-2">
            <div class="w-8 h-8 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white text-sm shadow-md">
              🤖
            </div>
            <div class="flex flex-col items-start">
              <div class="message-bubble bg-gray-100 text-gray-800 px-4 py-2 rounded-2xl max-w-[80%]">
                {{ msg.ai }}
              </div>
            </div>
          </div>
        </div>
        
        
        <!-- 加载指示器 -->
        <div v-if="aiLoading" class="flex justify-start">
          <div class="bg-gray-100 px-4 py-2 rounded-2xl">
            <div class="loading-dots flex gap-1">
              <span class="w-2 h-2 bg-gray-400 rounded-full"></span>
              <span class="w-2 h-2 bg-gray-400 rounded-full"></span>
              <span class="w-2 h-2 bg-gray-400 rounded-full"></span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="p-4 border-t">
        <div class="flex gap-2">
          <input
            v-model="aiInput"
            @keydown.enter="sendAIMessage"
            placeholder="输入您的问题..."
            class="flex-1 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            :disabled="aiLoading"
          />
          <button
            @click="sendAIMessage"
            :disabled="!aiInput.trim() || aiLoading"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { RouterLink, useRouter, useRoute } from 'vue-router';
import { ref, nextTick, computed } from 'vue';
import { useUserStore } from '../stores/user';

// 临时解决方案：直接定义函数
async function logout() {
  localStorage.removeItem('auth_token');
}

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const showSidebar = ref(false);
const showFab = ref(false);
const showAIChat = ref(false);
const aiMessages = ref([]);
const aiInput = ref('');
const aiLoading = ref(false);
const chatContainer = ref(null);

// 菜单项样式计算属性
const getMenuItemClass = (path: string) => {
  return [
    'block px-3 py-2 rounded transition-all duration-200',
    route.path === path 
      ? 'bg-primary text-white font-medium shadow-md' 
      : 'hover:bg-gray-100 text-gray-700 hover:text-gray-900'
  ];
};

// 切换悬浮菜单
function toggleFab() {
  showFab.value = !showFab.value;
}

// 打开AI助手悬浮窗口
async function goToAIChat() {
  showFab.value = false;
  showAIChat.value = true;
  
  // 加载历史记录
  await loadChatHistory();
}

// 跳转到主页
function goToHome() {
  showFab.value = false;
  router.push('/');
}

// 发送AI消息
async function sendAIMessage() {
  if (!aiInput.value.trim() || aiLoading.value) return;
  
  const userMessage = aiInput.value.trim();
  aiInput.value = '';
  aiLoading.value = true;
  
  // 添加用户消息（带时间戳）
  aiMessages.value.push({ 
    user: userMessage, 
    timestamp: new Date().toISOString() 
  });
  
  try {
    await startAIStreaming(userMessage);
  } catch (error) {
    console.error('AI对话失败:', error);
    aiMessages.value.push({ 
      ai: '抱歉，AI助手暂时无法响应，请稍后重试。',
      timestamp: new Date().toISOString()
    });
  } finally {
    aiLoading.value = false;
    scrollToBottom();
  }
}

// 流式AI对话
async function startAIStreaming(input) {
  const token = localStorage.getItem('auth_token');
  if (!token) {
    aiMessages.value.push({ ai: '请先登录后再使用AI助手。' });
    return;
  }

  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/ai/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ userInput: input })
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('无法读取响应流');
    }
    
    const decoder = new TextDecoder();
    let buffer = '';

    // 添加AI消息占位符（带时间戳）
    aiMessages.value.push({ 
      ai: '', 
      timestamp: new Date().toISOString() 
    });
    const aiMessageIndex = aiMessages.value.length - 1;


    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }

      // 解码数据并添加到缓冲区
      buffer += decoder.decode(value, { stream: true });
      
      // 按行分割数据
      const lines = buffer.split('\n');
      
      // 保留最后一个可能不完整的行
      buffer = lines.pop() || '';

      for (const line of lines) {
        const trimmedLine = line.trim();
        
        if (trimmedLine.startsWith('data:')) {
          try {
            const jsonStr = trimmedLine.slice(5); // 去掉 'data:' 5个字符
            const data = JSON.parse(jsonStr);
            
            if (data.content) {
              // 从当前消息中获取已有内容
              const currentContent = aiMessages.value[aiMessageIndex].ai || '';
              const newContent = currentContent + data.content;
              
              // 使用nextTick确保DOM更新
              await new Promise(resolve => {
                aiMessages.value[aiMessageIndex].ai = newContent;
                // 强制触发Vue响应式更新
                aiMessages.value = [...aiMessages.value];
                setTimeout(resolve, 10); // 短暂延迟确保渲染
              });
              
              scrollToBottom();
            }
            
            if (data.isFinish) {
              return;
            }
          } catch (e) {
            console.warn('解析SSE数据失败:', e, '原始数据:', trimmedLine);
          }
        }
      }
    }
  } catch (error) {
    console.error('流式对话失败:', error);
    throw error;
  }
}

// 加载对话历史
async function loadChatHistory() {
  const token = localStorage.getItem('auth_token');
  if (!token) return;

  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/ai/chat/history?page=0&size=10`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }

    const data = await response.json();
    if (data.chats && data.chats.length > 0) {
      // 转换历史记录格式
      const historyMessages: any[] = [];
      data.chats.forEach((chat: any) => {
        historyMessages.push({
          user: chat.userInput,
          timestamp: chat.createdAt
        });
        historyMessages.push({
          ai: chat.aiResponse,
          timestamp: chat.createdAt
        });
      });
      aiMessages.value = historyMessages;
    }
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('加载对话历史失败:', error);
  }
}

// 判断是否应该显示时间
function shouldShowTime(index: number) {
  if (index === 0) return true; // 第一条消息总是显示时间
  
  const currentMsg = aiMessages.value[index];
  const prevMsg = aiMessages.value[index - 1];
  
  if (!currentMsg.timestamp || !prevMsg.timestamp) return false;
  
  // 条件1：时间间隔超过5分钟
  const currentTime = new Date(currentMsg.timestamp);
  const prevTime = new Date(prevMsg.timestamp);
  const diffMinutes = (currentTime.getTime() - prevTime.getTime()) / (1000 * 60);
  const timeCondition = diffMinutes > 5;
  
  // 条件2：每隔6轮对话（每6条消息）
  const messageCount = index + 1;
  const roundCondition = messageCount % 6 === 0;
  
  // 两个条件是或的关系
  return timeCondition || roundCondition;
}

// 格式化时间
function formatTime(timestamp: string) {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 如果是今天
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }
  
  // 如果是昨天
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (date.getDate() === yesterday.getDate()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }
  
  // 其他情况显示完整日期
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 滚动到底部
function scrollToBottom() {
  if (chatContainer.value) {
    // 使用requestAnimationFrame确保DOM更新后再滚动
    requestAnimationFrame(() => {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    });
  }
}

async function handleLogout() {
  try {
    await logout();
    userStore.logout();
    router.push('/login');
  } catch (error) {
    console.error('登出失败:', error);
    // 即使登出失败，也清除本地状态
    userStore.logout();
    router.push('/login');
  }
}
</script>

<style scoped>
/* 悬浮按钮动画 */
.rotate-45 {
  transform: rotate(45deg);
}

/* 菜单项淡入动画 */
.animate-fade-in {
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 悬浮按钮悬停效果 */
button:hover {
  transform: scale(1.05);
}

/* 菜单项悬停效果 */
.space-y-3 > button:hover {
  transform: translateX(-5px);
}

/* AI对话窗口动画 */
.ai-chat-window {
  animation: slideInUp 0.3s ease-out;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 消息气泡动画 */
.message-bubble {
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载指示器动画 */
.loading-dots span {
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style>